package bootstrap;

import handler.EchoServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class EchoServer {
    private final int port;

    public EchoServer(int port){
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        if(args.length != 1){
            System.out.printf("Usage:" + EchoServer.class.getSimpleName() + "<port>");
        }
        // 设置端口
        int port = Integer.parseInt(args[0]);
        new EchoServer(port).start();
    }

    /**
     * 配置channel，把有关的入站消息通知给echoserverhandler
     */
    public void start() throws InterruptedException {
        final EchoServerHandler echoServerHandler = new EchoServerHandler();
        // 创建EventLoopGroup
        EventLoopGroup group = new NioEventLoopGroup();
        // 创建ServerBootstrap
        ServerBootstrap b = new ServerBootstrap();
        b.group(group)
                .channel(NioServerSocketChannel.class)
                // 指定端口号
                .localAddress(new InetSocketAddress(port))
                // 添加一个EchoServerHandler到子channel的chanelpipeline中
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(echoServerHandler);
                    }
                });
        // 异步地绑定服务器，调用sync方法阻塞直到绑定完成
        try {
            ChannelFuture future = b.bind().sync();
            // 获取channel的closeFuture，并且阻塞当前线程直到它完成
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            // 关闭Eventloop，释放所有资源
            group.shutdownGracefully().sync();
        }

    }
}
